const canvas = document.getElementById("canvas1");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let particleArray = [];
let aaa = 1;

// function drawStar(cx,cy,spikes,outerRadius,innerRadius)
function drawStar(cx, cy, spikes, outerRadius, innerRadius) {
    var rot = Math.PI / 2 * 3;
    var x = cx;
    var y = cy;
    // 实质为：step = (Math.PI * 2 ) / (spikes * 2)
    var step = Math.PI / spikes;

    ctx.beginPath();
    ctx.moveTo(cx, cy - outerRadius)
    // spikes控制边数，由于循环体里面重复调用了两次ctx.lineTo，所以绘制出的多边形为spikes的2倍
    for (i = 0; i < spikes; i++) {
        x = cx + Math.cos(rot) * outerRadius;
        y = cy + Math.sin(rot) * outerRadius;
        ctx.lineTo(x, y)
        rot += step

        x = cx + Math.cos(rot) * innerRadius;
        y = cy + Math.sin(rot) * innerRadius;
        ctx.lineTo(x, y)
        rot += step
    }
    ctx.lineTo(cx, cy - outerRadius);
    ctx.closePath();
    ctx.lineWidth = 5;
    ctx.strokeStyle = 'gold';
    ctx.stroke();
}

class Particle {
    constructor(moveRadius, step, position, size) {
        this.moveRadius = moveRadius;
        this.step = step;
        this.position = position;
        this.size = size;
    }
    draw() {
        ctx.beginPath();
        drawStar(Math.cos(this.position) * this.moveRadius + canvas.width / 3,
            Math.sin(this.position) * this.moveRadius + canvas.height / 3, 3, this.size, this.size);
        ctx.closePath();
        ctx.strokeStyle = "pink";
        ctx.stroke();
    }
    update() {
        // 控制多边形的位移
        this.position += this.step;
        // 重绘
        this.draw();
    }
}

// create particle array 
function init() {
    particleArray = [];
    // 控制单元生成的数量
    for (let i = 0; i < 50; i++) {
        let moveRadius = Math.random() * canvas.width;
        // 控制旋转速度
        let step = (Math.random() * 0.005) + 0.005;
        let position = Math.random() * (Math.PI * 2);
        // 控制多边形大小
        let size = Math.random() * 50;

        particleArray.push(new Particle(moveRadius, step, position, size));
    }
}

// animation loop
function animate() {
    requestAnimationFrame(animate);
    ctx.fillStyle = 'rgba(0,0,0,.01)';
    // 清空画布，可以理解为帧
    ctx.fillRect(0, 0, innerWidth, innerHeight);

    for (let i = 0; i < particleArray.length; i++) {
        particleArray[i].update();
    }
}
init();
animate();

// RESIZE SETTING - empty and refill particle array every time window changes size + change canvas size
window.addEventListener('resize',
    function () {
        canvas.width = innerWidth;
        canvas.height = innerHeight;
        init();
    }
)